package com.tongji.housediy.view
{
	import com.adobe.cairngorm.persistence.restricted.statement.ObjectUtil;
	import com.tongji.housediy.events.CantavilEvent.GetAllCityEvent;
	import com.tongji.housediy.events.CantavilEvent.GetCantavilEvent;
	import com.tongji.housediy.events.ChangeStateEvent;
	import com.tongji.housediy.events.TypeXMLAdminEvent;
	import com.tongji.housediy.events.UpdateRatioCompEvent;
	import com.tongji.housediy.events.UpdateViewControlEvent;
	import com.tongji.housediy.events.commonEvent.ChangeData3D;
	import com.tongji.housediy.events.commonEvent.ExchangeDataEvent;
	import com.tongji.housediy.events.commonEvent.GridContainerEvent;
	import com.tongji.housediy.events.commonEvent.ResetRadioGroupEvent;
	import com.tongji.housediy.events.commonEvent.RoomNameAdminEvent;
	import com.tongji.housediy.events.commonEvent.RulerAdminEvent;
	import com.tongji.housediy.events.commonEvent.SetCompStateEvent;
	import com.tongji.housediy.events.commonEvent.ShowHideTitleWindowEvent;
	import com.tongji.housediy.events.designEvent.SaveDeleteDesignEvent;
	import com.tongji.housediy.model.CompEnableStateModel;
	import com.tongji.housediy.model.ExchangeDataModel;
	import com.tongji.housediy.model.GoodsModel;
	import com.tongji.housediy.model.RightCompStateModel;
	import com.tongji.housediy.model.RightListStateModel;
	import com.tongji.housediy.model.UserInforModel;
	import com.tongji.housediy.model.ViewModel;
	import com.tongji.housediy.service.CantavilService;
	import com.tongji.housediy.utils.LoadAdmin;
	import com.tongji.housediy.utils.PopUpAdmin;
	import com.tongji.housediy.utils.ShareAdmin;
	import com.tongji.housediy.view.components.AbstractDrawingRoom;
	import com.tongji.housediy.view.components.Furniture;
	import com.tongji.housediy.view.components.GridContainer;
	import com.tongji.housediy.view.components.IndependentFloor;
	import com.tongji.housediy.view.components.InteriorWall;
	import com.tongji.housediy.view.components.NormalDoor;
	import com.tongji.housediy.view.components.NormalWindow;
	import com.tongji.housediy.view.components.OpeningWall;
	import com.tongji.housediy.view.components.RoomBorder;
	import com.tongji.housediy.view.components.RoomFloor;
	import com.tongji.housediy.view.skins.MyCustomMenuBarItem;
	import com.tongji.housediy.view.titlewindows.CantavilTitleWindow;
	import com.tongji.housediy.view.titlewindows.LoginTitleWindow;
	import com.tongji.housediy.view.titlewindows.OpenDesignTitleWindow;
	import com.tongji.housediy.view.titlewindows.SaveDesignTitleWindow;
	import com.tongji.housediy.view.titlewindows.SaveSuccessTitleWindow;
	import com.tongji.housediy.vo.Goods;
	import com.tongji.housediy.vo.House;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.GraphicsBitmapFill;
	import flash.display.InteractiveObject;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import flash.net.FileReference;
	import flash.net.NetConnection;
	import flash.net.Responder;
	import flash.net.SharedObject;
	import flash.net.URLLoader;
	import flash.utils.ByteArray;
	
	import mx.binding.utils.BindingUtils;
	import mx.controls.Alert;
	import mx.controls.Image;
	import mx.controls.Menu;
	import mx.controls.menuClasses.MenuBarItem;
	import mx.core.UIComponent;
	import mx.events.CloseEvent;
	import mx.events.MenuEvent;
	import mx.graphics.ImageSnapshot;
	import mx.graphics.codec.JPEGEncoder;
	import mx.managers.BrowserManager;
	import mx.managers.IBrowserManager;
	import mx.managers.PopUpManager;
	import mx.utils.ObjectUtil;
	import mx.utils.URLUtil;
	
	import org.robotlegs.base.EventMap;
	import org.robotlegs.mvcs.Mediator;
	
	import spark.components.TitleWindow;

	/**
	 * 
	 * @author yanghanbing
	 * 2011/4/07
	 */
	public class MenuBarCompMediator extends Mediator
	{
		[Inject]
		public var view:MenuBarComp;
		
		[Inject]
		public var roomModel:ExchangeDataModel;
		
		[Inject]
		public var goodsModel:GoodsModel;

		[Inject]
		public var userModel:UserInforModel;
		
		[Inject]
		public var service:CantavilService;
		
		[Inject]
		public var stateModel:RightCompStateModel;
		
		[Inject]
		public var indexModel:RightListStateModel;
		
		[Inject]
		public var viewModel:ViewModel;
		
		private var selectedComp:UIComponent;
		private var nc:NetConnection;
		public var roomsXML:XML = 
			<rooms time="" name="">			  
			</rooms>;
		
		override public function onRegister():void
		{
			view.addEventListener(MenuEvent.ITEM_CLICK, onClickItemHandler);
			dispatch(new GetCantavilEvent(GetCantavilEvent.GET_CANTAVIL));
			dispatch(new GetAllCityEvent(GetAllCityEvent.GET_ALL_CITYS));
			
			addContextListener(ChangeStateEvent.ROOM_OPENED, setSaveAsEnabled, ChangeStateEvent);
		}
		
		public function setSaveAsEnabled(event:ChangeStateEvent):void
		{
			BindingUtils.bindProperty(view, "saveAs", roomModel, "isOpened");
		}
		
		public function onClickItemHandler(event:MenuEvent):void
		{
		    var currentEventName:String = event.item.@eventName;
			switch(currentEventName)
			{
				case "newDesign":
					newDesign();
					break;
				case "openDesign":
					openDesign();
					break;
				case "saveDesign":
					saveDesign();
					break;
				case "saveDesignAs":
					saveDesignAs();
					break;
				case "cantavilEnter":
					cantavilEnter();
					break;
				case "renewDesign":
					renewDesign();
					break;
				case "2DView":
					changeTo2DView();
					break;
				case "3DView":
					changeTo3DView();
					break;
				case "showRule":
					showRule();
					break;
				case "showRoomName":
					showRoomName();
					break;
				case "sinaBtn":
					shareTosinaBtn();
					break;
				case "tencentBtn":
					shareTotencent();
					break;
				case "renrenBtn":
					shareTorenren();
					break;
				case "kaixinBtn":
					shareTokaixin();
					break;
				case "export":
					exportJPG();
					break;
			}
		}
		
		protected function exportJPG():void
		{
			var roomCount:int = roomModel.gridContainer.numChildren;
			if (roomCount > 0)
			{
				var minX:Number = 10000;
				var minY:Number = 10000;
				var maxX:Number = -1;
				var maxY:Number = -1;
				var target:UIComponent = roomModel.gridContainer;
				var boundingBox:Rectangle;
				for (var i:int = 0; i < roomModel.gridContainer.numChildren; i++)
				{
					if ((roomModel.gridContainer.getChildAt(i) is AbstractDrawingRoom) && !(roomModel.gridContainer.getChildAt(i) is IndependentFloor))
					{
						var host:AbstractDrawingRoom = roomModel.gridContainer.getChildAt(i) as AbstractDrawingRoom;
						boundingBox = host.getRect(host.parent);
						if (boundingBox.x <= minX)
							minX = boundingBox.x;
						if (boundingBox.y <= minY)
							minY = boundingBox.y;
						if (boundingBox.x + boundingBox.width >= maxX)
							maxX = boundingBox.x + boundingBox.width;
						if (boundingBox.y + boundingBox.height >= maxY)
							maxY = boundingBox.y + boundingBox.height;
					}					
				}
				var matrix:Matrix = new Matrix();
				matrix.translate(-minX + 32, -minY + 32);
				var bitmapData:BitmapData = new BitmapData(maxX - minX + 64, maxY - minY + 64);
				bitmapData.draw(target,matrix); 
				var jpg:JPEGEncoder = new JPEGEncoder(); 
				var jpgByteArray:ByteArray = jpg.encode(bitmapData); 
				var fr:FileReference = new FileReference(); 
				fr.save(jpgByteArray, 'export.jpg');
			}
			else
				Alert.show("请您先进行设计");	
		}
		
		private function shareTosinaBtn():void
		{
			ShareAdmin.shareAdmin("sina", "test", "http://space.rryjw.com/Member/Photo/Details.aspx?UserID=43716&PhotoID=2826");
		}
		
		private function shareTotencent():void
		{
			ShareAdmin.shareAdmin("tencent", "test", "http://space.rryjw.com/Member/Photo/Details.aspx?UserID=43716&PhotoID=2826");
		}
		
		private function shareTorenren():void
		{
			ShareAdmin.shareAdmin("renren", "test", "http://space.rryjw.com/Member/Photo/Details.aspx?UserID=43716&PhotoID=2826");
		}
		
		private function shareTokaixin():void
		{
			ShareAdmin.shareAdmin("kaixin", "test", "http://space.rryjw.com/Member/Photo/Details.aspx?UserID=43716&PhotoID=2826");
		}
		
		private function showRoomName():void
		{
			dispatch(new RoomNameAdminEvent(RoomNameAdminEvent.SHOW_HIDE_ROOM_NAME));
			dispatch(new RulerAdminEvent(RulerAdminEvent.HIDE_ALL_RULERS));
			dispatch(new ShowHideTitleWindowEvent(ShowHideTitleWindowEvent.HIDE_TITLE_WINDOW));
		}
		
		private function showRule():void
		{
			dispatch(new RulerAdminEvent(RulerAdminEvent.SHOW_HIDE_RULERS));
		}
		
		private function changeTo2DView():void
		{
			viewModel.changeTo2DView();
		}
		
		private function changeTo3DView():void
		{
			viewModel.changeTo3DView();
		}
		
		private function newDesign():void
		{
			if(roomModel.gridContainer.numChildren > 0)
			{
				PopUpAdmin.popupCenterWindow("saveVerify", view.parent, mediatorMap);				
			}
			else
				PopUpAdmin.popupCenterWindow("entryTitle", view.parent, mediatorMap,true,"haveStarted");			
		}
		
		private function alertClickHandler(event:CloseEvent):void
		{
			if(event.detail == Alert.YES)
			{
				saveDesign();
			}
			else
			{
				var roomCount:int = roomModel.gridContainer.numChildren;
				for(var i:int; i < roomCount; i++)
				{
					roomModel.gridContainer.removeChildAt(roomModel.gridContainer.numChildren - 1);
				}
			}
		}
		
		private function openDesign():void
		{
			if (!userModel.isLogined)
			{
				var enterWindow:LoginTitleWindow = new LoginTitleWindow();
				enterWindow.name = "openDesign";
				PopUpManager.addPopUp(enterWindow, view.parent, true);
				PopUpManager.centerPopUp(enterWindow);
				mediatorMap.createMediator(enterWindow);
			}
			else
			{
				PopUpAdmin.popupCenterWindow("openDesignTitle", view.parent, mediatorMap);
			}
		}
		
		public function open(event:SaveDeleteDesignEvent):void
		{
			for(var i:int = 0; i < roomModel.roomXML.rooms.room.length(); i++)
			{
				var room:AbstractDrawingRoom = new AbstractDrawingRoom();
				
				// 顶点赋值
				var tempString:String = roomModel.roomXML.rooms.room[i].@vertices.toString();				
				var arr:Array = tempString.split(",", tempString.length) as Array;				
				room._vertices = new Vector.<Number>();										
				for(var a:int = 0; a < arr.length; a++)
				{
					room._vertices.push(arr[a]);
				}
				
				// curveVector 赋值
				var tempString2:String = roomModel.roomXML.rooms.room[i].@curveVector.toString();				
				var arr2:Array = tempString2.split(",", tempString.length) as Array;
				if (tempString2 == "")
					arr2 = new Array();
				room.curveVector = new Vector.<int>();
				for(var j:int = 0; j < arr2.length; j++)
				{
					room.curveVector.push(arr2[j]);
				}
				
				// x, y, borderLength, height, roomType 属性赋值
				room.x = roomModel.roomXML.rooms.room[i].@x;
				room.y = roomModel.roomXML.rooms.room[i].@y;
				room.borderLength = roomModel.roomXML.rooms.room[i].@borderCount.toString();
				room.height = roomModel.roomXML.rooms.room[i].@height;				
				room.roomType = "room";
				
				// 重绘 roomFloor 并且赋值
				var tempNumber:int = i;
				var loader:Loader = LoadAdmin.loadBitmapData(roomModel.roomXML.rooms.room[i].floor[0].@mapSrc.toString());
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadFloorCompleteHandler);
				function loadFloorCompleteHandler(event:Event):void
				{
					event.target.removeEventListener(Event.COMPLETE, loadFloorCompleteHandler);
					
					room.roomFloor.materialBitmapData = event.target.content.bitmapData;
					room.roomFloor.stroke = new GraphicsBitmapFill(room.roomFloor.materialBitmapData);
					
					var floorGoods:Goods = goodsModel.getFloorGoodsByID(int(roomModel.roomXML.rooms.room[0].floor[0].@goodsID));
					
					room.roomFloor.hostGoods = floorGoods;
					room.roomFloor.selectedColorID = int(roomModel.roomXML.rooms.room[tempNumber].floor[0].@colorID);
					room.roomFloor.selectedSizeID = int(roomModel.roomXML.rooms.room[tempNumber].floor[0].@modelID);
					room.roomFloor.dragPicSrc = roomModel.roomXML.rooms.room[0].floor[tempNumber].@mapSrc as String;
					
					room.roomFloor.reDraw(room.borderLength);
				}
				
				room.drawing();
				roomModel.gridContainer.addChild(room);
				room.parentGridContainer = roomModel.gridContainer;
			}
		}
		
		/*private function loadFloorCompleteHandler(event:Event):void
		{
			event.target.removeEventListener(Event.COMPLETE, loadFloorCompleteHandler);
			
			tempRoomFloor.materialBitmapData = event.target.content.bitmapData;
			tempRoomFloor.stroke = new GraphicsBitmapFill(tempRoomFloor.materialBitmapData);
			
			var floorGoods:Goods = goodsModel.getFloorGoodsByID(int(roomModel.roomXML.rooms.room[0].floor[0].@goodsID));
			
			tempRoomFloor.hostGoods = floorGoods;
			tempRoomFloor.selectedColorID = int(roomModel.roomXML.rooms.room[0].floor[0].@colorID.toString());
			tempRoomFloor.selectedSizeID = int(roomModel.roomXML.rooms.room[0].floor[0].@modelID.toString());
			tempRoomFloor.dragPicSrc = roomModel.roomXML.rooms.room[0].floor[0].@mapSrc as String;
			
			tempRoomFloor.reDraw(int(roomModel.roomXML.rooms.room[0].floor[0].@borderCount));
		}*/
		
		private function saveDesign():void
		{			
			var sharedObject:SharedObject = SharedObject.getLocal("User");
			var roomCount:int = roomModel.gridContainer.numChildren;
			if (roomCount <= 0)
			{
				Alert.show("请您先进行设计");
			}
			else if (roomCount > 0)
			{
				if (!userModel.isLogined)
				{
					var enterWindow:LoginTitleWindow = new LoginTitleWindow();
				    enterWindow.name = "saveDesign";
				    PopUpManager.addPopUp(enterWindow, view.parent, true);
				    PopUpManager.centerPopUp(enterWindow);
				    mediatorMap.createMediator(enterWindow);
				}
				else if(userModel.isLogined && !roomModel.isOpened)
				{
					PopUpAdmin.popupCenterWindow("saveDesignTitle", view.parent, mediatorMap);
				}
				else if(userModel.isLogined && roomModel.isOpened)
				{
					Alert.show("保存修改");
				}
			}
		}
		
		/*private function getImg():BitmapData
		{
			var minX:Number = 10000;
			var minY:Number = 10000;
			var maxX:Number = -1;
			var maxY:Number = -1;
			var target:UIComponent = roomModel.gridContainer;
			var boundingBox:Rectangle;
			for (var i:int = 0; i < roomModel.gridContainer.numChildren; i++)
			{
				if ((roomModel.gridContainer.getChildAt(i) is AbstractD rawingRoom) && !(roomModel.gridContainer.getChildAt(i) is IndependentFloor))
				{
					var host:AbstractDrawingRoom = roomModel.gridContainer.getChildAt(i) as AbstractDrawingRoom;
					boundingBox = host.getRect(host.parent);
					if (boundingBox.x <= minX)
						minX = boundingBox.x;
					if (boundingBox.y <= minY)
						minY = boundingBox.y;
					if (boundingBox.x + boundingBox.width >= maxX)
						maxX = boundingBox.x + boundingBox.width;
					if (boundingBox.y + boundingBox.height >= maxY)
						maxY = boundingBox.y + boundingBox.height;
				}					
			}
			var matrix:Matrix = new Matrix();
			matrix.translate(-minX + 32, -minY + 32);
			var bitmapData:BitmapData = new BitmapData(maxX - minX + 64, maxY - minY + 64);
			bitmapData.draw(target,matrix); 
			return bitmapData;
		}
		
		private function saveHouse():void
		{
			var house:House = new House();
			house.buildingID = 0;
			if(userModel.userID == '')
			{
				Alert.show("请先登录");
			}
			else
			{
				var encode:JPEGEncoder = new JPEGEncoder(100);
				var byte:ByteArray = encode.encode(getImg());
				
				nc = new NetConnection();
				var rp:Responder = new Responder(successResult, errStatus);
				nc.client = nc;
				
				nc.objectEncoding = flash.net.ObjectEncoding.AMF3;
				//nc.connect("http://10.60.0.118/housediy/Gateway.aspx");
				nc.connect("http://design.rryjw.com/Gateway.aspx");
				var date:Date = new Date();
				var fileName:String = userModel.userID.toString() + date.fullYear.toString() + date.month.toString() + 
					date.date.toString() + date.hours.toString() + date.minutes.toString() + date.seconds.toString();
				nc.call("HouseDiyService.HouseDiyAction.getPic",rp, byte, fileName);
				var loader:URLLoader = new URLLoader;
				// loader.load(req);
				house.designerID = int(userModel.userID);
				house.houseArea = 0;
				house.houseCreateDate = new Date();
				house.houseCreator = "caddy";
				house.houseName = "";
				house.housePicSrc = fileName +".jpg";
				house.houseRemark = "";
				house.houseType = "type1";
				house.houseModelSrc = roomModel.saveHouse().toString();
				
				dispatch(new SaveHouseEvent(SaveHouseEvent.SAVE_HOUSE, house, roomModel.roomXML));
		 }
		}
		
		private function successResult(result:String):void 
		{
			//关闭连接
			nc.close();
		}
		
		private function errStatus(result:String):void 
		{
			nc.close();
		}*/
		
		private function saveDesignAs():void
		{
			//saveDesign();
			//roomModel.saveHouse();
			var sharedObject:SharedObject = SharedObject.getLocal("User");
			if(roomModel.gridContainer.numChildren != 0 && userModel.userID != "")
			{var saveRoomWindow:SaveDesignTitleWindow = new SaveDesignTitleWindow();
				PopUpManager.addPopUp(saveRoomWindow, view.parent, true);
				PopUpManager.centerPopUp(saveRoomWindow);
				mediatorMap.createMediator(saveRoomWindow);
			}
			else if(roomModel.gridContainer.numChildren == 0 && userModel.userID != "")
			{
				Alert.show("请先设计");
				
			}
			else if(roomModel.gridContainer.numChildren != 0 && userModel.userID == "")
			{
				/*var saveNothingWindow:LoginTitleWindow = new LoginTitleWindow();
				saveNothingWindow.name = "saveAs";
				PopUpManager.addPopUp(saveNothingWindow, view.parent, true);
				PopUpManager.centerPopUp(saveNothingWindow);
				mediatorMap.createMediator(saveNothingWindow);*/
			}
			else
			{
				/*var saveAsNothingWindow:LoginTitleWindow = new LoginTitleWindow();
				saveNothingWindow.name = "nothingSave";
				PopUpManager.addPopUp(saveAsNothingWindow, view.parent, true);
				PopUpManager.centerPopUp(saveAsNothingWindow);
				mediatorMap.createMediator(saveAsNothingWindow);*/
			}			
		}
		
	
		
		private function cantavilEnter():void
		{
			var cantavilWindow:CantavilTitleWindow = new CantavilTitleWindow();
			PopUpManager.addPopUp(cantavilWindow, view.parent, true);
			PopUpManager.centerPopUp(cantavilWindow);
			mediatorMap.createMediator(cantavilWindow);
		}
		
		private function renewDesign():void
		{
			if(roomModel.gridContainer.numChildren > 0)
			{
				Alert.yesLabel = "保存设计";
				Alert.noLabel = "重新设计";
				Alert.show("是否放弃已有设计，重新开始设计", "!", 3, view.stage as Sprite, alertClickHandler);
			}
		}
		
	}
}